package com.oneplatform.support.auth;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.mendmix.common.MendmixBaseException;
import com.mendmix.common.http.HttpRequestEntity;
import com.mendmix.common.util.ResourceUtils;
import com.mendmix.gateway.api.AccountApi;
import com.mendmix.gateway.model.AccountScope;

@Service
public class DefaultAccountApi implements AccountApi {

	@Value("${user.service.baseUrl:http://oneplatform-user-svc}/validate")
	private String userValidateUrl;
	
	@Value("${user.service.baseUrl:http://oneplatform-user-svc}/scopes")
	private String userScopeUrl;
	
	private Map<String, String> superAdmins = ResourceUtils.getMappingValues("mendmix.security.superadmin.mapping");


	@Override
	public LoginUserInfo validateAccount(String type,String accountName, String password) throws MendmixBaseException {
		LoginUserInfo authUser;
		if(superAdmins.containsKey(accountName)) {
			if(!BCrypt.checkpw(password, superAdmins.get(accountName))) {
				throw new MendmixBaseException("账号不存在或密码错误");
			}
			authUser = new LoginUserInfo();
			authUser.setAdmin(true);
			authUser.setName(accountName);
		}else {
			Map<String, String> param = new HashMap<>(2);
			param.put("account", accountName);
			param.put("password", password);
			authUser = HttpRequestEntity.post(userValidateUrl).body(param).execute().toObject(LoginUserInfo.class);
			
			if(type != null) {
				List<AccountScope> scopes = findAccountScopes(authUser.getId());
				AccountScope scope = null;
				if(scopes != null) {
					scope = scopes.stream().filter(o -> type.equals(o.getPrincipalType())).findFirst().orElse(null);
				}
				if(scope == null) {
					throw new MendmixBaseException(403, "未授权登录(TYPE_NOT_MATCH)");
				}
				authUser.setDefaultTenantId(scope.getTenantId());
				authUser.setPrincipalType(scope.getPrincipalType());
				authUser.setPrincipalId(scope.getPrincipalId());
				authUser.setAdmin(scope.isAdmin());	
			}	
		}
		
		return authUser;
	}

	@Override
	public List<AccountScope> findAccountScopes(String accountId) {
		List<AccountScope> scopes = HttpRequestEntity.get(userScopeUrl).queryParam("userId", accountId).execute().toList(AccountScope.class);
		return scopes;
	}

}
